Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
Add a function to the prototype with access to "this"

On the one hand I can assign a new function to an object with Object.defineProperty(...).

Then I tried to assign a function directly to the NodeList Prototype. But somehow it doesn't work properly. What am I doing wrong?

Object.defineProperty(
  NodeList.prototype,
  'lastElement', { 
    get: function() {
      return this[this.length - 1].textContent;
    }
  }
);

NodeList.prototype.firstElement = () => {
   return this[0].textContent;
}

const h = document.querySelectorAll('span');
console.log('#last:', h.lastElement);
console.log('#first:', h.firstElement);
<div>
  <span>1</span>
  <span>2</span>
</div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Arrow functions () => {...} are not just a different syntax that behaves the same way, they actually handle the this keyword differently.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#arrow_functions_used_as_methods

If you switch to using the traditional function syntax, this will behave as you are expecting.

Additionally, you've defined firstElement as a regular function, not a getter function, so you will need to call it like this

console.log('#first:', h.firstElement());

Object.defineProperty(
  NodeList.prototype,
  'lastElement', { 
    get: function() {
      return this[this.length - 1].textContent;
    }
  }
);

NodeList.prototype.firstElement = function() {
   return this[0].textContent;
}

const h = document.querySelectorAll('span');
console.log('#last:', h.lastElement);
console.log('#first:', h.firstElement());
<div>
  <span>1</span>
  <span>2</span>
</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda